package thread.内部api;

import java.util.concurrent.CountDownLatch;

/**
 * Created mangcao with 2020/4/3 18:16
 * Description:
 */
public class CountDownLatchDe {

    public static void main(String[] args) throws Exception{


//        test();

//        test1();

        invoke();
    }


    /**
     * 计数器 , 等待队列线程组await住  ， 用消费线程组countdown减少计数 ，直到减少为0
     *
     * @throws InterruptedException
     */
    public static void invoke() throws InterruptedException {
        /*创建CountDownLatch实例,计数器的值初始化为3*/
        final CountDownLatch downLatch = new CountDownLatch(2);

        for (int i = 0; i < 8; i++) {

            int finalI1 = i;
            new Thread(() -> {
                /*任务完成后调用CountDownLatch的countDown()方法*/
                try {
                    downLatch.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("downLatch.await finish:" + finalI1);
            }).start();
        }


        /*创建三个线程,每个线程等待1s,表示执行比较耗时的任务*/
        for (int i = 0; i < 5; i++) {

            final int num = i;
            Thread thread = new Thread(() -> {
                try {
                    Thread.sleep(1000 * (num + 1));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                System.out.println(String.format("countDown thread %d ", num));
                /*任务完成后调用CountDownLatch的countDown()方法*/
                downLatch.countDown();

            });
            thread.start();
        }

        System.out.println("main start");

        /*主线程调用await()方法,等到其他三个线程执行完后才继续执行*/
        downLatch.await();

        System.out.println("main end");
    }


    private static void test1() throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(1);

        for (int i = 0; i < 4; i++) {
            countDownLatch.countDown();
        }

        countDownLatch.await();

        System.out.println(99);
    }





    private static void test2() {

        CountDownLatch countDownLatch = new CountDownLatch(1);

        Thread thread = new Thread(() -> {

//            try {
//                countDownLatch.await();
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }

            Thread.currentThread().interrupt();

            System.out.println("睡眠结束");
        });

        thread.start();
        System.out.println(thread.isInterrupted());

        countDownLatch.countDown();
        System.out.println(thread.isInterrupted());

    }
}
